<?php
/**
 * 销售退货单
 * Created by PhpStorm.
 * User: echa
 * Date: 2018/2/1
 * Time: 11:12
 */

namespace App\Services\Warehouse;


class SalesReturnsService extends PublicService {
    //销售退货表单ID
    //protected $Formid = 'SAL_RETURNSTOCK';

    public function __construct()
    {
        parent::__construct(config('k3cloud.SalesReturns'));
    }


    /**
     * 保存
     * 1.formid：业务对象表单Id（必录）
     * 2.data：Json格式数据（详情参考Json格式数据）（必录）
     * 2.1.Creator：创建者名字（非必录）
     * 2.2.NeedUpDateFields：需要保存的字段,格式["fieldkey1","fieldkey2","entitykey1",...]，数组类型(非必录)
     * 2.3.NeedReturnFields：需要返回的结果字段,格式["fieldkey","entitykey.fieldkey",...]（非必录）
     * 2.4.IsDeleteEntry：是否删除分录，默认True删除（非必录）
     * 2.5.SubSystemId：菜单所在子系统Id（非必录）
     * 2.6.IsVerifyBaseDataField：是否验证所有的基础资料，默认False不验证（非必录）
     * 2.7.IsEntryBatchFill：是否批量填充分录：默认为Ture（非必录）
     * 2.8.Model：表单实体数据（必录）
     */
    public function SaveSalesReturns($arrdata = [],$is_submitandaudit=false)
    {
            $goods=$this->PostGoodsData($arrdata['GoodsData']);
            if(!$goods){
                return false;
            }
            if(empty($arrdata['FID'])){
                $arrdata['FID']=0;
            }
            if(empty($arrdata['FBillNo'])){
                $arrdata['FBillNo']="";
            }
            if(empty($arrdata['ReturnType'])){
                $arrdata['ReturnType']="004"; //其他
            }
            if(empty($arrdata['order_sn'])){
                $arrdata['order_sn']='';
            }
            if(empty($arrdata['discountamount'])){
                $arrdata['discountamount']=0;
            }
            if(empty($arrdata['freight'])){
                $arrdata['freight']=0;
            }
            $data = [
                    "FID"=>$arrdata['FID'],
                    "FBillTypeID"=>[
                        "FNumber"=>"XSTHD01_SYS"
                    ],
                    "FBillNo"=>$arrdata['FBillNo'],
                    "FDate"=>date('Y-m-d H:i:s',time()),
                    "FDiscountAmount"=>$arrdata['discountamount'],
                    "FFreight"=>$arrdata['freight'],
                    "FSaleOrgId"=>[
                        "FNumber"=>config('k3cloud.organization')
                    ],
                    "FSaledeptid"=>[
                        "FNumber"=>""
                    ],
                    "FRetcustId"=>[
                        "FNumber"=>config('k3cloud.appcustomer')
                    ],
                    "FReturnReason"=>[
                        "FNumber"=>$arrdata['ReturnType']
                    ],
                    "FHeadLocId"=>[
                        "FNUMBER"=>""
                    ],
                    "FCorrespondOrgId"=>[
                        "FNumber"=>""
                    ],
                    "FTransferBizType"=>[
                        "FNumber"=>"OverOrgSal"
                    ],
                    "FSaleGroupId"=>[
                        "FNumber"=>""
                    ],
                    "FSalesManId"=>[
                        "FNumber"=>""
                    ],
                    "FStockOrgId"=>[
                        "FNumber"=>config('k3cloud.organization')
                    ],
                    "FStockDeptId"=>[
                        "FNumber"=>""
                    ],
                    "FStockerGroupId"=>[
                        "FNumber"=>""
                    ],
                    "FStockerId"=>[
                        "FNumber"=>""
                    ],
                    "FHeadNote"=>"",
                    "FOrderSn"=>$arrdata['order_sn'],
                    "FReceiveCustId"=>[
                        "FNumber"=>config('k3cloud.appcustomer')
                    ],
                    "FReceiveAddress"=>"",
                    "FSettleCustId"=>[
                        "FNumber"=>config('k3cloud.appcustomer')
                    ],
                    "FReceiveCusContact"=>[
                        "FName"=>""
                    ],
                    "FPayCustId"=>[
                        "FNumber"=>config('k3cloud.appcustomer')
                    ],
                    "FOwnerTypeIdHead"=>"BD_OwnerOrg",
                    "FOwnerIdHead"=>[
                        "FNumber"=>""
                    ],
                    "FScanBox"=>"",
                    "FCDateOffsetUnit"=>"",
                    "FCDateOffsetValue"=>0,
                    "FIsTotalServiceOrCost"=>false,
                    "SubHeadEntity"=>[
                        "FSettleCurrId"=>[
                            "FNumber"=>"PRE001"
                        ],
                        "FThirdBillNo"=>"",
                        "FThirdBillId"=>"",
                        "FThirdSrcType"=>"",
                        "FSettleOrgId"=>[
                            "FNumber"=>config('k3cloud.organization')
                        ],
                        "FSettleTypeId"=>[
                            "FNumber"=>""
                        ],
                        "FChageCondition"=>[
                            "FNumber"=>""
                        ],
                        "FPriceListId"=>[
                            "FNumber"=>""
                        ],
                        "FDiscountListId"=>[
                            "FNumber"=>""
                        ],
                        "FLocalCurrId"=>[
                            "FNumber"=>"PRE001"
                        ],
                        "FExchangeTypeId"=>[
                            "FNumber"=>"HLTX01_SYS"
                        ],
                        "FExchangeRate"=>1.0
                    ],
                    "FEntity"=>$goods
                ];
        if($is_submitandaudit){
            $return=$this->save($data);
            if(empty($return['Id'])){
                return false;
            }
            $submitreturn=$this->SubmitSalesReturns([$return['Number']]);
            if(empty($submitreturn['Id'])){
                return false;
            }
            $auditreturn=$this->AuditSalesReturns([$return['Number']]);
            if(empty($auditreturn['Id'])){
                return false;
            }
            return $auditreturn;
        }else{
            return $this->save($data);
        }
    }



    /**
    提交
     *
     * 1.formid：业务对象表单Id（必录）
    2.data：Json格式数据（详情参考Json格式数据）（必录）
    2.1.CreateOrgId：创建者组织，字符串类型（非必录）
    2.2.Numbers：单据编号集合，格式["billNo1","billNo1",...]，数组类型（必录）
     */

    public function  SubmitSalesReturns($Numbers=[]){
        return $this->submit($Numbers);
    }

    /**
    审核
     * 1.formid：业务对象表单Id（必录）
    2.data：Json格式数据（详情参考Json格式数据）（必录）
    2.1.CreateOrgId：创建者组织，字符串类型（非必录）
    2.2.Numbers：单据编号集合，格式["billNo1","billNo1",...]，数组类型（必录）
     */
    public function AuditSalesReturns($Numbers=[]){
        return $this->audit($Numbers);
    }


    /**
    反审核
     * 1.formid：业务对象表单Id（必录）
    2.data：Json格式数据（详情参考Json格式数据）（必录）
    2.1.CreateOrgId：创建者组织，字符串类型（非必录）
    2.2.Numbers：单据编号集合，格式["billNo1","billNo1",...]，数组类型（必录）
     */
    public function unAuditSalesReturns($Numbers=[]){
        return $this->unAudit($Numbers);
    }

    /**
     *单据列表查询
     * 1.data：Json格式数据（详情参考Json格式数据）（必录）
    1.1.FormId：业务对象表单Id（必录）
    1.2.FieldKeys：字段keys，字符串类型用逗号分隔，比如"key1,key2..."（必录）
    1.3.FilterString：过滤（非必录）  FNumber=''
    1.4.OrderString：排序字段（非必录）
    1.5.TopRowCount：总行数（非必录）
    1.6.StartRow：开始行（非必录）
    1.7.Limit：最大行数，不能超过2000（非必录）
     */
    public function ExecuteBillQuerySalesReturns($FieldKeys='',$FilterString='',$OrderString='',$StartRow=0,$Limit=20)
    {
            if (empty($FieldKeys)) {
                $FieldKeys='FBillNo,FCustomerID,FDocumentStatus,FCarriageNO,FCreatorId,FCreateDate';
            }
            return $this->ExecuteBillQuery($FieldKeys,$FilterString,$OrderString,$OrderString,$StartRow,$Limit);
    }


    public function PostGoodsData($GoodsData){
        if(!is_array($GoodsData)){
            return false;
        }
        $goods=array();
        $FOwnerTypeBDSupplier=config('k3cloud.FOwnerTypeBDSupplier');
        $FOwnerTypeBDOwnerOrg=config('k3cloud.FOwnerTypeBDOwnerOrg');
        foreach ($GoodsData as $k=>$v){
            $FOwnerFNumber=config('k3cloud.organization');
            if($v['k3_vmi']){
                $FOwnerTypeID=$FOwnerTypeBDSupplier;
                $FOwnerFNumber=$v['k3_supplier_sn'];
            }else{
                $FOwnerTypeID=$FOwnerTypeBDOwnerOrg;
            }
            if(empty($v['goods_price'])){
                $v['goods_price']=0.0;
            }
            $goods[]=[
                "FENTRYID"=>null,
                "FRowType"=>"Standard",
                "FMapId"=>[
                    "FNumber"=>""
                ],
                "FMaterialId"=>[
                    "FNumber"=>$v['goods_sn']
                ],
                "FUnitID"=>[
                    "FNumber"=>$v['spec_unit']
                ],
                "FInventoryQty"=>0.0,
                "FRealQty"=>$v['goods_number'],
                "FParentMatId"=>[
                    "FNumber"=>""
                ],
                //"FPrice"=>0.0,
                "FTaxPrice"=>$v['goods_price'],
                "FIsFree"=>false,
                "FTaxCombination"=>[
                    "FNumber"=>""
                ],
                //"FEntryTaxRate"=>17.00,
                "FBOMId"=>[
                    "FNumber"=>""
                ],
                "FReturnType"=>[
                    "FNumber"=>"THLX01_SYS"
                ],
                "FOwnerTypeId"=>$FOwnerTypeID,
                "FOwnerId"=>[
                    "FNumber"=>$FOwnerFNumber
                ],
                "FProduceDate"=>null,
                "FExpiryDate"=>null,
                "FStockId"=>[
                    "FNumber"=>$v['StockNubmer'],// 仓库编号
                ],
                "FStocklocId"=>[
                    "FSTOCKLOCID__FF100001"=>[
                        "FNUMBER"=>""
                    ]
                ],
                "FStockstatusId"=>[
                    "FNumber"=>"KCZT01_SYS"
                ],
                "FDeliveryDate"=>date('Y-m-d H:i:s',time()),
                "FMtoNo"=>null,
                "FNote"=>null,
                "FDiscountRate"=>0.0,
                "FAuxUnitQty"=>0.0,
                "FExtAuxUnitId"=>[
                    "FNumber"=>""
                ],
                "FExtAuxUnitQty"=>0.0,
                "FSalCostPrice"=>0.0,
                "FISCONSUMESUM"=>"0",
                "FLot"=>[
                    "FNumber"=>""
                ],
                "FSalUnitID"=>[
                    "FNumber"=>$v['spec_unit']
                ],
                "FSalUnitQty"=>$v['goods_number'],
                "FSalBaseQty"=>$v['goods_number'],
                "FPriceBaseQty"=>$v['goods_number'],
                "FProjectNo"=>null,
                "FQualifyType"=>"",
                "FEOwnerSupplierId"=>[
                    "FNumber"=>""
                ],
                "FIsOverLegalOrg"=>false,
                "FESettleCustomerId"=>[
                    "FNumber"=>""
                ],
                "FThirdEntryId"=>null,
                "FSOEntryId"=>0,
                "FPriceListEntry"=>[
                    "FNumber"=>""
                ],
                "FARNOTJOINQTY"=>$v['goods_number'],
                "FIsReturnCheck"=>false
            ];
        }
        return $goods;
    }


    /***
     * 退货退款(包括线上和收银)
     * @param array $data
     * @param WarehouseService $warehouseService
    @author echa
     * @return array|bool
     */
    public function SalesReturnRefunds(array $data,$type=1){
        $warehouseService=new WarehouseService();
        $StockNubmer=$data['k3_number'];
        $goods=$data['goods'];
        if(count($goods)<=0){
            return false;
        }
        if($type==1){
            //根据仓库编号筛选相同分组下面指定仓库类型为退货仓库数据
            $sales_return_stock=$warehouseService->GetWarehouseTypeInfo($StockNubmer,'C');
            if(!$sales_return_stock){
                return false;
            }
            $sales_return_nubmer=$sales_return_stock[0]['FNumber'];//相同分组对应退货仓
            $StockNubmer=$sales_return_nubmer;
        }
        $srgoods=array();
        foreach ($goods as $k=>$v){
            $srgoods[]=[
                'goods_sn'=>$v['goods_sn'],
                'spec_unit'=>$v['spec_unit'],
                'goods_number'=>$v['goods_number'],
                'k3_supplier_sn'=>$v['k3_supplier_sn'],
                'k3_vmi'=>$v['k3_vmi'],
                'StockNubmer'=>$StockNubmer,
            ];
        }
        if($type==1){
            $savedata=[
                'ReturnType'=>'002',
                'order_sn'=>$data['order_sn'],
                'freight'=>$data['freight'],
                'discountamount'=>$data['discountamount'],
                'GoodsData'=>$srgoods
            ];
            return $this->SaveSalesReturns($savedata,true);
        }elseif($type==2){
            $savedata=[
                'ReturnType'=>'005',
                'order_sn'=>$data['order_sn'],
                'freight'=>$data['freight'],
                'discountamount'=>$data['discountamount'],
                'GoodsData'=>$srgoods
            ];
            return $this->SaveSalesReturns($savedata,true);
        }

    }

    /***
     * 漏送退款
     * @param array $data
    @author echa
     * @return array|bool
     */
    public function MissFeedRefunds(array $data){
        $StockNubmer=$data['k3_number'];
        $goods=$data['goods'];
        if(count($goods)<=0){
            return false;
        }
        foreach ($goods as $k=>$v){
            $srgoods[]=[
                'goods_sn'=>$v['goods_sn'],
                'spec_unit'=>$v['spec_unit'],
                'goods_number'=>$v['goods_number'],
                'k3_supplier_sn'=>$v['k3_supplier_sn'],
                'k3_vmi'=>$v['k3_vmi'],
                'StockNubmer'=>$StockNubmer,
            ];
        }
        $savedata=[
            'ReturnType'=>'001',
            'order_sn'=>$data['order_sn'],
            'freight'=>$data['freight'],
            'discountamount'=>$data['discountamount'],
            'GoodsData'=>$srgoods
        ];
        return $this->SaveSalesReturns($savedata,true);
    }
}